use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Debug, Deserialize, Clone)]
pub struct Config {
    pub host: String,
    pub port: u16,
    pub refresh_token: String,
    pub auth_tokens: Vec<String>,
    pub api_url: String,
}

impl Config {
    pub fn load() -> Result<Self> {
        
        let possible_paths = [
            std::env::current_dir()?.join("config.json"),
            std::env::current_exe()?.parent().unwrap().join("config.json"),
            PathBuf::from("config.json"),
        ];

        let config: Config = possible_paths
            .iter()
            .find_map(|path| {
                if let Ok(content) = std::fs::read_to_string(path) {
                    serde_json::from_str(&content).ok()
                } else {
                    None
                }
            })
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "config.json not found in any of these locations:\n{}\nPlease create one using config.json.example as a template.",
                    possible_paths.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n")
                )
            })?;

        if config.auth_tokens.is_empty() {
            anyhow::bail!("auth_tokens array cannot be empty in config.json");
        }

        Ok(config)
    }
} 